﻿using System;
using System.Collections.Generic;
using IQIGame.Onigao.GamePlay;
using LFloatMath.Math;

namespace IQIGame.Onigao.Logic
{
    public class FormulaFunction_CustomProperty : FormulaFunction
    {
        public override EFormulaFunctionType funcType => EFormulaFunctionType.bCustomProperty;

        public override void Calculate(Stack<IFormulaOperand> rCalopd, IFormulaObject rSelf, IFormulaObject rTarget, Formula rFromFormula)
        {
            IFormulaOperand opd1 = rCalopd.Pop();
            IFormulaOperand opd2 = rCalopd.Pop();
            IFormulaOperand opd3 = rCalopd.Pop();
            if (opd1.TryGet<LFloat>(out var op1, rSelf, rTarget, rFromFormula) &&
                opd2.TryGet<LFloat>(out var op2, rSelf, rTarget, rFromFormula) &&
                opd3.TryGet<LFloat>(out var op3, rSelf, rTarget, rFromFormula))
            {
                var bSelf = op1.ToInt() == 1;
                var nProperty = op2.ToInt();
                var rUnit = (bSelf ? rSelf : rTarget);

                IFormulaOperand result = FormulaHelper.FetchOperand(EFormulaOperandType.Num);
                if (rUnit != null)
                {
                    switch (op3.ToInt())
                    {
                        case 0:
                        {
                            // int
                            var nNum = rUnit.GetCustomProperty<int>((ECustomProperty)nProperty);
                            result.Set(nNum.ToLFloat());
                            break;
                        }
                        case 1:
                        {
                            // bool
                            var bValue = rUnit.GetCustomProperty<bool>((ECustomProperty)nProperty);
                            result.Set(bValue ? LFloat.one : LFloat.zero);
                        }
                            break;
                    }
                }
                rCalopd.Push(result);
            }
            else
            {
                throw new Exception($"{funcType} func need two number");
            }

            opd1.TryFree();
            opd2.TryFree();
            opd3.TryFree();
        }
    }
}